$(document).ready(function() {
    $("#dob").datepicker({
        minDate: new Date(1900, 1 - 1, 1),
        maxDate: "+0",
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd",
        yearRange: "1900:+0",
        hideIfNoPrevNext: true,
        showButtonPanel: true,
        showOptions: {direction: "down"}
    });
    $("#date").datepicker({
        minDate: new Date(),
        maxDate: '+3m',
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd",
        hideIfNoPrevNext: true,
        showButtonPanel: true
    });
});

function showQRCode(itemcode){
    $('#itemqrcode').html('');
    $('#picture').foundation('reveal', 'open');
    var itemqrcode = '<img style="width: 100%" src="qrgenerator.php?param='+itemcode+'">';
    var desc = '<p>Use this to redeem for the souvenir in station counter</p>';
    $('#itemqrcode').html(itemqrcode);
    $('#description').html(desc);
}

function changePassword() {
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    $.ajax({
        type: 'POST',
        url: 'userAction.php',
        data: $('#passwordform').serialize(),
        success: function(result) {
            if (!result.error) {
                $('#overlay').fadeOut('fast');
                $('#info').fadeIn('slow').addClass('success').removeClass('alert').html(result.message).delay(4000).fadeOut('slow');
                $('#passwordform').each(function() {
                    this.reset();
                });
            } else {
                $('#overlay').fadeOut('fast');
                $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
            }
        }
    });
}

function promptPassword() {
    $('#promptpw').addClass('hidden-field');
    $('#lblpass').removeClass('hidden-field');
    $('#iptpass').removeClass('hidden-field');
    $('#realsubmit').removeClass('hidden-field');
}

function nonEmptyValidation(element) {
    var elementLength = element.value.length;
    var info = document.getElementById(element.id + "Err");
    if (elementLength === 0) {
        $('#' + element.id).addClass('error');
        $("#" + info.id).text("Required Field").show();
        return false;
    } else {
        $('#' + element.id).removeClass('error');
        $('#' + info.id).hide();
        return true;
    }
}

function validatePassword(element) {
    var pwLength = element.value.length;
    var info = document.getElementById(element.id + "Err");
    if (nonEmptyValidation(element)) {
        if (pwLength < 6) {
            $('#' + element.id).addClass('error');
            $("#" + info.id).text("Password must more than 6 character").show();
            return false;
        } else {
            $('#' + element.id).removeClass('error');
            $("#" + info.id).hide();
            return true;
        }
    } else {
        return false;
    }
}

function checkPassword(uid) {
    if ($('#password').val() != '') {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $('#password').removeClass('error');
        $('#passwordErr').addClass('hidden-field');
        $.ajax({
            type: 'POST',
            url: 'userAction.php',
            data: {action: 'checkPassword', uid: uid, password: $('#password').val()},
            success: function(result) {
                if (!result.error) {
                    updateDetails();
                } else {
                    $('#overlay').fadeOut('fast');
                    $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                }
            }
        });
    } else {
        $('#passwordErr').removeClass('hidden-field');
        $('#password').addClass('error');
    }
}

function updateDetails() {
    $.ajax({
        type: 'POST',
        url: 'userAction.php',
        data: $('#profileform').serialize(),
        success: function(result) {
            if (!result.error) {
                $('#overlay').fadeOut('fast');
                $('#info').fadeIn('slow').addClass('success').removeClass('alert').html(result.message).delay(4000).fadeOut('slow');
                $('#formsec').hide();
            } else {
                $('#overlay').fadeOut('fast');
                $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
            }
        }
    });
}

function getRoute() {
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    $.ajax({
        type: 'POST',
        url: 'action.php',
        data: {action: $('#getroute').val()},
        success: function(result) {
            if (!result.error) {
                console.log(result.message);
                $('#route').empty().append(new Option('Select a route', 0));
                console.log(result.message.length);
                for (var i = 0; i < result.message.length; i++) {
                    $('#route').append(new Option(result.message[i].routeName, result.message[i].rid));
                }
                $(document).foundation('forms');
                $('#overlay').fadeOut('fast');
            } else {
                $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                $(document).foundation('forms');
                $('#overlay').fadeOut('fast');
            }
        }
    });
}

function getOrigin() {
    if ($('#route').val() != 0) {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: {action: $('#getorigin').val(), rid: $('#route').val()},
            success: function(result) {
                if (!result.error) {
                    $('#origin').empty().append(new Option('Select origin', 0));
                    for (var i = 0; i < result.message.length - 1; i++) {
                        $('#origin').append(new Option(result.message[i].stationName, result.message[i].sid));
                    }
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                } else {
                    $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                }
            }
        });
    }
}

function getDestination() {
    if ($('#origin').val() != 0 && $('#route').val() != 0) {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: {action: $('#getdestin').val(), rid: $('#route').val(), sid: $('#origin option:selected').index()},
            success: function(result) {
                if (!result.error) {
                    $('#destin').empty().append(new Option('Select destination', 0));
                    for (var i = 0; i < result.message.length; i++) {
                        $('#destin').append(new Option(result.message[i].stationName, result.message[i].sid));
                    }
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                } else {
                    $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                }
            }
        });
    }
}

function obtainSchedule() {
    var route = $('#route').val();
    var origin = $('#origin').val();
    var destin = $('#destin').val();
    var date = $('#date').val();
    if ((route != 0) && (origin != 0) && (destin != 0) && (date != '')) {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: $('#ticketform').serialize(),
            success: function(result) {
                if (!result.error) {
                    $('#schedule').html(result.message);
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                } else {
                    $('#schedule').html('');
                    $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                    $('#overlay').fadeOut('fast');
                }
            }
        });
    } else {
        $('#info').fadeIn('slow').addClass('alert').removeClass('success').html('Please make selection first').delay(4000).fadeOut('slow');
    }

}

function proceedBooking() {
    var index = $('#schedule input[name=index]:checked').val();
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    $.ajax({
        type: 'POST',
        url: 'action.php',
        data: {action: $('#action').val(),
            shid: $('#shid' + index).val(),
            schedule: $('#schedule' + index).val(),
            departure: $('#departure' + index).val(),
            arrival: $('#arrival' + index).val(),
            origin: $('#origin' + index).val(),
            destin: $('#destin' + index).val(),
            route: $('#route' + index).val(),
            date: $('#date').val(),
            fare: $('#fare' + index).val(),
            emptyseat: $('#seat' + index).val()
        },
        success: function(data) {
            if (!data.error) {
                $('#overlay').fadeOut('fast');
                window.location.replace('ticketing.php');
            } else {
                $('#overlay').fadeOut('fast');
                $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(data.message).delay(4000).fadeOut('slow');
            }
        }
    });
}

function filterItem(element) {
    $('#info').hide();
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    var id = element.id;
    $('dd').removeClass('active');
    $('#' + id).addClass('active');
    var itemtype;
    switch (id) {
        case 'all':
            getAllItem();
            break;
        case 'cpn':
            itemtype = 'coupon';
            getFilteredItem(itemtype);
            break;
        case 'crd':
            itemtype = 'credit';
            getFilteredItem(itemtype);
            break;
        case 'svr':
            itemtype = 'souvenir';
            getFilteredItem(itemtype);
            break;
    }
}

function getAllItem() {
    $.post('action.php', {
        action: 'getRedeemableItem'
    }, function(data) {
        if (!data.error) {
            $('#redeemitems').html(data.message);
            $('#overlay').fadeOut('fast');
            $('#redeemitems').show();
        } else {
            $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(data.message).delay(4000).fadeOut('slow');
            $('#overlay').fadeOut('fast');
        }
    });
}
function getFilteredItem(itemtype) {
    $.post('action.php', {
        action: 'getRedeemableItem',
        type: itemtype
    }, function(data) {
        if (!data.error) {
            $('#redeemitems').html(data.message);
            $('#overlay').fadeOut('fast');
            $('#redeemitems').show();
        } else {
            $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(data.message).delay(4000).fadeOut('slow');
            $('#overlay').fadeOut('fast');
        }
    });
}

function redeemItem(itemcode, pointrequired) {
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    var icno = $('#icno').val();
    $.post('action.php', {
        action: 'redeemItem', icno: icno, itemcode: itemcode, point: pointrequired
    }, function(data) {
        if (!data.error) {
            $('#info').fadeIn('slow').addClass('success').removeClass('alert').html(data.message + '<a href="#" class="close">&times;</a>');
            $('#cumulatedpoint').html(data.point);
            $('#point').val(data.point);
            $('#redeemitems').hide();
            $('#overlay').fadeOut('fast');
        } else {
            $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(data.message).delay(4000).fadeOut('slow');
            $('#overlay').fadeOut('fast');
        }
    });
}

function getRedeemHistory() {
    $('#history').html('');
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    var icno = $('#icno').val();
    $.post('action.php', {
        action: 'getHistory', icno: icno
    }, function(data) {
        if (!data.error) {
            $('#history').html(data.message);
            $('#overlay').fadeOut('fast');
            $('.footable').footable();
        } else {
            $('#history').html(data.message);
            $('#overlay').fadeOut('fast');
        }
    });
}

function getScheduleStatus() {
    if ($('#route').val() != 0) {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: {action: $('#getorigin').val(), rid: $('#route').val()},
            success: function(result) {
                if (!result.error) {
                    $('#origin').empty().append(new Option('Select origin', 0));
                    for (var i = 0; i < result.message.length - 1; i++) {
                        $('#origin').append(new Option(result.message[i].stationName, result.message[i].sid));
                    }
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                } else {
                    $('#info').fadeIn('slow').addClass('alert').removeClass('success').html(result.message).delay(4000).fadeOut('slow');
                    $(document).foundation('forms');
                    $('#overlay').fadeOut('fast');
                }
            }
        });
    }
}